package com.bjx.flow.mmx.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjx.flow.mmx.bean.MmxFlowData;
import com.bjx.flow.mmx.domain.entity.MmxFlowDefinitionEntity;
import com.bjx.flow.mmx.mapper.MmxFlowDefinitionMapper;
import com.bjx.flow.mmx.service.MmxFlowDataService;
import com.bjx.flow.mmx.service.MmxFlowDefinitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @desc: 流程定义服务实现
 * @author: liushuai
 * @date: 2023/05/17
 */
@Service
public class MmxFlowDefinitionServiceImpl extends ServiceImpl<MmxFlowDefinitionMapper, MmxFlowDefinitionEntity> implements MmxFlowDefinitionService {
    @Autowired
    private MmxFlowDefinitionMapper flowDefinitionMapper;
    @Resource
    private MmxFlowDataService flowDataService;


    @Override
    public MmxFlowDefinitionEntity deploy(String flowData) {
        MmxFlowDefinitionEntity flowDefinition = null;
        //校验流程数据
        MmxFlowData flowObj = flowDataService.checkFlowData(flowData);
        MmxFlowDefinitionEntity definition = MmxFlowDefinitionEntity.builder()
                .definitionKey(flowObj.getDefinitionKey())
                .flowData(flowData)
                .createTime(new Date())
                .build();
        synchronized (this){
            //查询最新的流程定义
            flowDefinition = selectFlowDefinitionByDefinitionKey(flowObj.getDefinitionKey());
            if(flowDefinition == null){
                definition.setVersion(1);
            }else {
                definition.setVersion(flowDefinition.getVersion()+1);
            }
            flowDefinitionMapper.insert(definition);
        }
        return definition;

    }


    public MmxFlowDefinitionEntity selectFlowDefinitionByDefinitionKey(String definitionKey) {
        LambdaQueryWrapper<MmxFlowDefinitionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MmxFlowDefinitionEntity::getDefinitionKey,definitionKey);
        wrapper.orderByDesc(MmxFlowDefinitionEntity::getVersion);
        Page<MmxFlowDefinitionEntity> page = flowDefinitionMapper.selectPage(new Page<>(1, 1), wrapper);
        List<MmxFlowDefinitionEntity> definitionEntitys = page.getRecords();
        if(CollectionUtil.isNotEmpty(definitionEntitys)){
            return  definitionEntitys.get(0);
        }
        return null;
    }

}
